from django.conf.urls.defaults import *
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect  
from django_websocket import require_websocket
from worker import Worker
from Queue import Queue
from pprint import pprint
from random import random


def base_view(request):
#    print request.session.session_key
#    print request.COOKIES
#    if 'nickname' in request.session:
    print 'base_view'
    print request.session.session_key
    print request.COOKIES
    print 'base_view'
    params = {}
    params['session_key'] = request.session.session_key
    params['host'] = request.get_host()

    
    if 'nickname' in request.session:
        params['nickname']= request.session['nickname'] 
    
    return render_to_response('index.html', params)

def set_nickname(request):
    request.session['nickname'] = request.GET['nickname']
    return base_view(request)


def start_thread(request):
    if settings.WSCHAT_WORKERS:   
        return HttpResponse('Workers ya iniciados')
    
    settings.WSCHAT_WORKERS = []
    settings.WSCHAT_QUEUE = Queue(0)
    
    workers = settings.WSCHAT_WORKERS 
    queue = settings.WSCHAT_QUEUE
        
    for i in range(0,  settings.WSCHAT_NUMBER_OF_WORKERS):
        worker = Worker(queue, i)
        workers.append(worker)
        workers[i].start()
    return HttpResponse('Workers iniciados')

def add_user(request):
    settings.WSCHAT_QUEUE.put((0, 'hola'))
    return HttpResponse('Usuario anadido')

@require_websocket
def echo(request):
    print 'echo'
    print request.session.session_key
    print request.COOKIES
    print 'echo'

    pprint(settings.WSCHAT_WEBSOCKETS)
    # ws = settings.WSCHAT_WEBSOCKETS.append('hola') 
    #this_session_key = request.session.session_key
    this_session_key = random()
    ws = settings.WSCHAT_WEBSOCKETS
    #ws[this_session_key]=request.websocket
    ws[this_session_key]=request.websocket
    print ws
    for message in request.websocket:
        print message
        for key in ws:
            ws[key].send(message)
    
    del ws[this_session_key]

#    print websockets

#        
#    for message in request.websocket:
#        settings.WSCHAT_QUEUE.put((0, message))
#    del settings.WSCHAT_WEBSOCKTS[request.session.session_key]
urlpatterns = patterns('',
                       url(r'^$', base_view),
                       url(r'^start_workers/$', start_thread),
                       url(r'^add_user/$', add_user),
                       url(r'^set_nickname/$', set_nickname),
                       url(r'^echo$', echo),
                       )                       